/**
 * Created by ospip on 2017/10/27.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class WeighedAverage implements Average {

    private static class WeighedItem {
        double weight;
        double data;
        public WeighedItem(double d, double w) {
            data = d;
            weight = w;
        }
        public WeighedItem() {
            this(0, 0);
        }
    }

    WeighedItem[] list;

    public WeighedAverage(WeighedItem[] l) {
        list = l;
    }

    public WeighedAverage() {
        list = new WeighedItem[0];
    }

    public WeighedAverage(String[] l) { // 数据，权重，数据，权重……
        list = new WeighedItem[l.length / 2];
        try {
            for (int i = 0; i < l.length; i++) {
                if (i % 2 == 0) list[i / 2].data = Double.parseDouble(l[i]);
                else list[i / 2].weight = Double.parseDouble(l[i]);
            }
        }
        catch (NumberFormatException e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public double average() {
        double sum = 0, cnt = 0;
        for (WeighedItem i : list) {
            sum += i.data * i.weight;
            ++cnt;
        }
        return sum / cnt;
    }
}
